//
//  YSRecommendCtrl.m
//  Yueshi
//
//  Created by Northwan on 15/7/16.
//  Copyright (c) 2015年 悦食中国. All rights reserved.
//  推荐首页

#import "YSRecommendCtrl.h"
#import "YSHomeDataTool.h"
#import "YSHomeCardImageView.h"
#import "YSCardList.h"
#import "YSAdvert.h"
#import "YSHeaderResult.h"
#import "YSCardImageResult.h"
#import "YSCardProdResult.h"
#import "YSCardBannerResult.h"
#import "YSCardGridResult.h"
#import "YSHomeBannerView.h"
#import "YSHomeProdListView.h"
#import "YSHomeCardGridView.h"
#import "YSHomeCardVideoView.h"
#import "YSLodingView.h"
#import "CartView.h"
#import "YSSearchCtrl.h"
#import <BaiduMapAPI/BMapKit.h>//refer all head file
#import "YSWhiteLineView.h"
#import "YSUpdateTipsView.h"
#import "CustomShowView.h"
#import "YSCommonReqTool.h"

@interface YSRecommendCtrl ()<UIScrollViewDelegate,BMKLocationServiceDelegate,BMKGeoCodeSearchDelegate>
@property (strong,nonatomic) UIScrollView *scrollView;
@property (assign,nonatomic) CGFloat currentY;
@property (strong,nonatomic) NSMutableArray *itemArray;
@property(nonatomic,strong)CartView *cartView;
@property(nonatomic,strong)BMKLocationService *locService;
@property (nonatomic, strong) UIView *videoView;
@property (nonatomic, assign) NSInteger pageIndex;
@property (strong, nonatomic) UIButton *backTopBtn;
@end

@implementation YSRecommendCtrl


-(NSMutableArray *)itemArray{
    if(!_itemArray){
        _itemArray = [NSMutableArray array];
    }
    return _itemArray;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    UIImage *logoImg = [UIImage imageNamed:@"home_title_logo"];
    UIImageView *titleLogoView  = [[UIImageView alloc]initWithImage:logoImg];
    self.navigationItem.titleView = titleLogoView;
    
    CartView *cartView = [[CartView alloc]initWithImage:@"btn_cart"];
    [cartView addTarget:self action:@selector(tapTitleRightItem:) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.rightBarButtonItem =  [[UIBarButtonItem alloc]initWithCustomView:cartView];
    _cartView = cartView;
    
    UIBarButtonItem *leftSearchItem = [UIBarButtonItem itemWithImageName:@"icon_home_search" highImageName:@"icon_home_search" target:self action:@selector(leftSearchClick)];
    self.navigationItem.leftBarButtonItem = leftSearchItem;
    
    _scrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 0, SCREENW, self.view.height - BottomTabarH - NavWithStatusBarH)];
    [_scrollView setAlwaysBounceVertical:YES];
    [_scrollView setDelegate:self];
    
    MJRefreshNormalHeader *header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [self headerRefresh];
    }];
    header.lastUpdatedTimeLabel.hidden = YES;
    MJRefreshBackNormalFooter *footer = [MJRefreshBackNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(footerRefresh)];
    _scrollView.header = header;
    _scrollView.footer = footer;
    _scrollView.userInteractionEnabled = YES;
    [self.view addSubview:_scrollView];
    
    [self initBaiduMapLocation];
    [self updateCartIndex];
    [self.scrollView.header beginRefreshing];
    
    _backTopBtn = [[UIButton alloc]init];
    _backTopBtn.frame = CGRectMake(SCREENW-50, _scrollView.height - 50, 40, 40);
    [_backTopBtn setBackgroundImage:[UIImage imageNamed:@"icon_back_top"] forState:UIControlStateNormal];
    [_backTopBtn addTarget:self action:@selector(toTop:) forControlEvents:UIControlEventTouchUpInside];
    [_backTopBtn setHidden:YES];
    [self.view addSubview:_backTopBtn];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(videoPlay:) name:KStopVideoPlayNortif object:nil];
    
    //检查升级
    [self upgrade];
}

-(void)leftSearchClick{
    //打开搜索界面
    CustomNavigationCtrl *nav = [[CustomNavigationCtrl alloc]initWithRootViewController:[[YSSearchCtrl alloc]init]];
    [self.navigationController presentViewController:nav animated:YES completion:nil];
}

-(void)updateCartIndex{
    //更新购物篮角标
    if(ISLOGIN){
        __weak typeof (self) weakSelf = self;
        [[YSCommonReqTool sharedTool] loadIndex:YSBadgeAllType callback:^(NSInteger count) {
            [weakSelf.cartView setNum:count];
        }];
    }else{
        [DefaultsHelper setInteger:0 forKey:kCartIndex];
    }
}

-(void)tapTitleRightItem:(UIBarButtonItem *)btnItem{
    [Utils showCartCtrl:self];
}

-(void)headerRefresh{
    self.pageIndex = -1;
    self.scrollView.footer.hidden = NO;
    [self requestData];
}

-(void)footerRefresh{
    self.pageIndex++;
    [self requestData];
}

-(void)checkRequestData{
    if(!self.itemArray.count){
        [self.scrollView.header beginRefreshing];
    }
}

-(void)requestData{
    [YSHomeDataTool getHomeInfo:self.pageIndex success:^(YSHomeInfoRes *result) {
        [self endRefresh];
        if(result.isSucc){
            [self dealData:result];
        }else{
            ShowEnterTips(result.data);
        }
    } failure:^(NSError *error) {
        [self endRefresh];
        ShowTips(kRequestFailure);
    }];
}

-(void)endRefresh{
    [_scrollView.header endRefreshing];
    [_scrollView.footer endRefreshing];
}

-(void)clearSubviews{
    NSArray *subviews = self.scrollView.subviews;
    for (UIView *subview in subviews) {
        if([subview isKindOfClass:[YSHomeCardImageView class]]
           ||
           [subview isKindOfClass:[YSHomeCardGridView class]]
           ||
           [subview isKindOfClass:[YSHomeBannerView class]]
           ||
           [subview isKindOfClass:[YSHomeProdListView class]]
           ||
           [subview isKindOfClass:[YSHomeCardVideoView class]]
           ||
           [subview isKindOfClass:[YSWhiteLineView class]]){
            [subview removeFromSuperview];
        }
    }
    self.currentY = 0;
}

-(void)dealData:(YSHomeInfoRes *)result{
    
    if(!result.cardList.count){
        self.scrollView.footer.hidden = YES;
        return;
    }
    
    if(self.pageIndex < 0){//下拉
        [self clearSubviews];
        [self.itemArray removeAllObjects];
        [self.itemArray addObjectsFromArray:result.cardList];
    }else {//上拉
        [self.itemArray addObjectsFromArray:result.cardList];
        YSWhiteLineView *view = [[YSWhiteLineView alloc] init];
        view.frame = CGRectMake(0, self.currentY, self.scrollView.width, YSPublicXInset);
        [self.scrollView addSubview:view];
         self.currentY = self.scrollView.contentSize.height + view.height;
    }
    
    for (YSCardList *card in result.cardList) {
        
        NSString *cardIcon =  card.cardIcon;
        NSString *cardDesc = card.cardIntrod;
        NSString *cardName = card.cardName;
        long long endTime = card.endTime;
        YSHeaderResult *headResult = [[YSHeaderResult alloc]init];
        [headResult setCardDesc:cardDesc];
        [headResult setCardIcon:cardIcon];
        [headResult setCardName:cardName];
        [headResult setEndTime:endTime];
        [headResult setIsMore:card.isMore];
        [headResult setId:card.id];
        
        if(card.cardTpl == CARD_BIG_IMAG_STYLE){
            
            YSHomeCardImageView *cardImageView  = [[YSHomeCardImageView alloc]initWithSourceType:HomeSourceType superCurrentY:self.currentY];
            [cardImageView setY:self.currentY];
            [self.scrollView addSubview:cardImageView];
            
            YSCardImageResult *result = [[YSCardImageResult alloc]init];
            [result setHeadResult:headResult];
            [result setAdvert:card.advert];
            
            [cardImageView setInfo:result];
            NSLog(@"cardImageView maxY :%f",CGRectGetMaxY(cardImageView.frame));
            self.currentY = CGRectGetMaxY(cardImageView.frame);
        }else
        
        if(card.cardTpl == CARD_GRID_STYLE){
            YSCardGridResult *result = [[YSCardGridResult alloc]init];
            [result setHeadResult:headResult];
            [result setAdvert:card.advert];
            
            YSHomeCardGridView *gridView = [[YSHomeCardGridView alloc]initWithSourceType:HomeSourceType];
            [gridView setY:self.currentY];
            [self.scrollView addSubview:gridView];
            [gridView setInfo:result];
            NSLog(@"gridView maxY :%f",CGRectGetMaxY(gridView.frame));
            self.currentY = CGRectGetMaxY(gridView.frame);
        }else
        
        if(card.cardTpl == CARD_BANNER_STYLE){
            YSCardBannerResult *result = [[YSCardBannerResult alloc]init];
            [result setAdvert:card.advert];
            YSHomeBannerView *bannerView = [[YSHomeBannerView alloc]initWithAdvert:result sourceType:HomeSourceType];
            [bannerView setFrame:CGRectMake(0, self.currentY, SCREENW, SCREENW/1.5)];
            [self.scrollView addSubview:bannerView];
            NSLog(@"bannerView maxY :%f",CGRectGetMaxY(bannerView.frame));
            self.currentY = CGRectGetMaxY(bannerView.frame);
        }else
        
        if(card.cardTpl == CARD_DETAIL_STYLE){
            YSCardProdResult *result = [[YSCardProdResult alloc]init];
            [result setHeadResult:headResult];
            [result setProdlist:card.productList];
            
            YSHomeProdListView *prodView = [[YSHomeProdListView alloc]initWithSourceType:HomeSourceType];
            [prodView setInfo:result];
            [prodView setY:self.currentY];
            [_scrollView addSubview:prodView];
            
            NSLog(@"prodView maxY :%f",CGRectGetMaxY(prodView.frame));
            self.currentY = CGRectGetMaxY(prodView.frame);
        }else
        
        if (card.cardTpl == CARD_VIDEO_STYLE) {
            YSHomeCardVideoView *cardVideoView  = [[YSHomeCardVideoView alloc]initWithSourceType:HomeSourceType superCurrentY:self.currentY];
            [cardVideoView setY:self.currentY];
            [self.scrollView addSubview:cardVideoView];
            
            YSCardImageResult *result = [[YSCardImageResult alloc]init];
            [result setHeadResult:headResult];
            [result setAdvert:card.advert];
            
            [cardVideoView setInfo:result];
            NSLog(@"cardVideoView maxY :%f",CGRectGetMaxY(cardVideoView.frame));
            self.currentY = CGRectGetMaxY(cardVideoView.frame);
        }
    }    
    NSLog(@"current maxY = %f  current ScreenH = %f",self.currentY,SCREENH);
    [_scrollView setContentSize:CGSizeMake(SCREENW, self.currentY)];
    NSLog(@"contentSize = %f",self.scrollView.contentSize.height);
}

-(void)initBaiduMapLocation{
    //set location accuracy，default：kCLLocationAccuracyBest
    [BMKLocationService setLocationDesiredAccuracy:kCLLocationAccuracyNearestTenMeters];
    //assign min distance update(meter)，default：kCLDistanceFilterNone
    [BMKLocationService setLocationDistanceFilter:100.f];
    //init BMKLocationService
    _locService = [[BMKLocationService alloc]init];
    _locService.delegate = self;
    //start LocationService
    [_locService startUserLocationService];
}
//implemention relevance delegate, deal with location info update ,deal with orientation update info
- (void)didUpdateUserHeading:(BMKUserLocation *)userLocation
{
    //NSLog(@"heading is %@",userLocation.heading);
}
//deal with location info update
- (void)didUpdateBMKUserLocation:(BMKUserLocation *)userLocation
{
    //NSLog(@"didUpdateUserLocation lat %f,long %f",userLocation.location.coordinate.latitude,userLocation.location.coordinate.longitude);
    if(userLocation.location){
        NSLog(@"\n百度到位置:\n  纬度lat:%f\n  经度lng:%f",userLocation.location.coordinate.latitude,userLocation.location.coordinate.longitude);
        BMKGeoCodeSearch *geoCodeSearch = [[BMKGeoCodeSearch alloc]init];
        geoCodeSearch.delegate  = self;
        //initialize geography encode class
        BMKReverseGeoCodeOption *reverseGeoCodeOption = [[BMKReverseGeoCodeOption alloc]init];
        //need backwards geography encode's location
        reverseGeoCodeOption.reverseGeoPoint = userLocation.location.coordinate;
        [geoCodeSearch reverseGeoCode:reverseGeoCodeOption];
        [_locService stopUserLocationService];
    }
}

-(void)onGetReverseGeoCodeResult:(BMKGeoCodeSearch *)searcher result:(BMKReverseGeoCodeResult *)result errorCode:(BMKSearchErrorCode)error{
    //get city
    NSString *city =  result.addressDetail.city;
    NSString *province = result.addressDetail.province;
    NSString *area = result.addressDetail.district;
    NSString *streetName = result.addressDetail.streetName;
    
    [DefaultsHelper setObject:province forKey:kLocationAddressProvince];
    [DefaultsHelper setObject:city forKey:kLocationAddressCity];
    [DefaultsHelper setObject:area forKey:kLocationAddressArea];
    [DefaultsHelper setObject:streetName forKey:kLocationAddressStreet];
}

-(void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    NSDictionary *userInfo = [DefaultsHelper dictionaryForKey:kRemotePushNortif];
    if (userInfo) {
        CustomNavigationCtrl *navCtl = (CustomNavigationCtrl *)self.navigationController;
        [navCtl dealNoti:userInfo isEnterForeground:YES];
        [DefaultsHelper setObject:nil forKey:kRemotePushNortif];
    }
    
    if(_cartView){
        NSInteger num = [DefaultsHelper integerForKey:kCartIndex];
        [_cartView setNum:num];
    }
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    
    NSLog(@"YSRecommendCtrl viewWillDisappear");
    
    [[NSNotificationCenter defaultCenter] postNotificationName:KStopVideoPlayNortif object:nil];
}

//scrollView滚动时，就调用该方法。任何offset值改变都调用该方法。即滚动过程中，调用多次
- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    if (self.videoView) {
        CGPoint point=scrollView.contentOffset;
        // 从中可以读取contentOffset属性以确定其滚动到的位置。
    
        // 注意：当ContentSize属性小于Frame时，将不会出发滚动
    
        CGRect rect = [self.videoView convertRect:self.videoView.frame toView:self.scrollView];
    
        if ((point.y > rect.size.height + rect.origin.y) || point.y + self.view.height < rect.origin.y) {
            [[NSNotificationCenter defaultCenter] postNotificationName:KStopVideoPlayNortif object:nil];
            self.videoView = nil;
        }
    }
    
    if(scrollView.contentOffset.y > SCREENH){
        [_backTopBtn setHidden:NO];
    }else{
        [_backTopBtn setHidden:YES];
    }
}

-(void)toTop:(UIButton *)toTopBtn{
    [UIView animateWithDuration:1.0 animations:^{
        [self.scrollView setContentOffset:CGPointMake(0, 0) animated:YES];
    } completion:^(BOOL finished) {
    }];
}

- (void)videoPlay:(NSNotification *)notify{
   self.videoView = [notify object];
}

- (void)upgrade{
        //显示是否有新版
        YSSetupInfoRes *app = [NSKeyedUnarchiver unarchiveObjectWithFile:YSAppInfoFilePath];
        if (app && [app.appVersion compare:[SystemUtil getAppVersion]]==NSOrderedDescending) {
            NSString *preSkipVersion = [DefaultsHelper stringForKey:kSkipUpgradeVersion];
            if (![NSString isBlankString:preSkipVersion] && [app.appVersion isEqualToString:preSkipVersion]) return ;

            //有新版
            YSUpdateTipsView *tipsView = [YSUpdateTipsView tipsView];
            tipsView.width = SCREENW;
            tipsView.appInfo = app;
        
            CustomShowView *showView = [[CustomShowView alloc] initWithCustomView:tipsView location:CustomShowViewLocationCenterType];

            [showView showWithAnim:YES];
        }
}

- (void)dealloc{
    self.videoView = nil;
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}


@end
